package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("file")
public class FileController {

    /**
     * @param file
     * @return com.changgou.entity.Result
     * @description: 上传文件
     * @author 大佬味的小男孩
     * @date 2020/07/17 18:33
     */
    @PostMapping("upload")
    public Result uploadFile(MultipartFile file) {
        try {
            //判断文件是否存在
            if (file == null) {
                throw new RuntimeException("文件不存在");
            }
            // 获取文件的完整名称
            String originalFilename = file.getOriginalFilename();

            if (StringUtils.isEmpty(originalFilename)) {
                throw new RuntimeException("文件不存在");
            }
            //获取文件的扩展名称
            String suName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //获取文件的内容
            byte[] bytes = file.getBytes();
            //创建文件上传的实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, bytes, suName);
            //工具类进行文件上传 并接受 返回参数 String []
            String[] upload = FastDFSClient.upload(fastDFSFile);
            // upload  包括 1.文件的组名  2.文件的路径信息
            //拼url
            String url = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];
            //将url 返回
            return new Result(true, StatusCode.OK, "文件上传成功", url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "文件上传失败");
    }
}
